/**
 * @Description: 消息管理
 * @author ourslookAdmin
 * @date 2019-04-24 19:24:42
 */
import React, { Fragment } from 'react';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import Modal from 'drag-modal';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Transfer,
  Spin,
  Tag,
  TreeSelect,
  BackTop,
  Tooltip,
  Icon,
  Table,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import { handleEditorupload, editorPreview ,editorProps} from '../../../utils/braft_editor_config';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class InfMessage extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    { title: '标题', dataIndex: 'messagetitle', width: 500, align: 'center', sorter: false },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      align: 'center',
      sorter: true,
      key: 'CreateTime',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('tinfmessage:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('tinfmessage:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: InfMessage.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      contentHtml: BraftEditor.createEditorState(''),
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'messagetitle',
      label: '标题',
      placeholder: '标题',
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        usertype: '',
      },
      showList: 2,
      contentHtml: BraftEditor.createEditorState(''),
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: selectedRows[0],
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].messagecontent),
    });
    this.getInfo(selectedRows[0].messageid);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].messagecontent),
    });
    this.getInfo(selectedRows[0].messageid);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const messageids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      messageids.push(selectedRows[i].messageid);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });

      requestPromise(`${getWebPath('/tinfmessage/delete')}`, {
        method: 'POST',
        body: messageids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const infMessage = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    if (infMessage.messagecontent.isEmpty()) {
      uiUtils.showMessage(`描述不能为空！`, 'error');
      return;
    }

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = infMessage.messageid == null ? '/tinfmessage/save' : '/tinfmessage/update';
        //对象删除一个属性
        //delete infMessage.xxxxPros;
        infMessage.messagecontent = infMessage.messagecontent.toHTML();

/*        if (this.editForm.state.userIds.length <= 0) {
          const userIds = [];
          for (let i = 0; i < this.editForm.state.allUserList.length; i += 1) {
            userIds.push(this.editForm.state.allUserList[i].user_id);
          }
          infMessage.userIds = userIds;
        }*/

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: infMessage,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!infMessage.messageid) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = messageid => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(`${getWebPath(`/tinfmessage/info/${messageid}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });

      if (res && res.code === 0) {
        const tInfMessage = res.tInfMessage;
        const userIds = tInfMessage.userIds === null ? [] : tInfMessage.userIds;
        const selectedRowKeys = [];
        userIds.forEach(item => {
          // eslint-disable-next-line radix
          selectedRowKeys.push(parseInt(item));
        });
        this.editForm.setState({
          selectedRowKeys,
          userIds: tInfMessage.userIds,
          userNames: tInfMessage.userNames,
        });
        this.setState({
          editModel: tInfMessage,
        });
      }
    });
  };
  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('/tinfmessage/list')}`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('tinfmessage:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('tinfmessage:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="MessageId"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 900 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                contentHtml={this.state.contentHtml}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default InfMessage;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    contentHtml: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    contentHtml: BraftEditor.createEditorState(''),
  };

  constructor(props) {
    super(props);
    this.state = {
      isShowUser: false,
     // allUserList: this.getSelectUser(),
      selectedRowKeys: [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  preview = () => {
    editorPreview(this.state.editorState.toHTML());
  };

  handleChange = targetKeys => {
    this.setState({targetKeys});
  };

  //获取用户list
  getUserList = (dir, key) => {
    requestPromise(`${getWebPath()}tinfmessage/getUserBySchoolId`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const userList = res.list;
        const userDatas = [];
        userList.forEach(r => {
          const data = {
            key: r.user_id,
            title: `${r.username} - ${r.mobile}`,// `${r.username} - ${r.mobile}`,
            description: `${r.username} - ${r.mobile}`, // `${r.username} - ${r.mobile}`,
            chosen: Math.random() * 2 > 1,
          };
          userDatas.push(data);
        });
        this.setState({
          userDatas,
        });
      }
    });
  };

  filterOption = (inputValue, option) => option.description.indexOf(inputValue) > -1 || option.description.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;

/*  getSelectUser = () => {
    const params = {
      schoolId: null,
      userTypes: this.props.model.usertype,
    };
    requestPromise(`${getWebPath()}tinfmessage/getUserBySchoolId`, {
      method: 'POST',
      body: params,
    }).then(res => {
      if (res && res.code === 0) {
        const datas = res.list;
        datas.forEach(d => {
          d.key = d.user_id;
        });
        this.setState({
          allUserList: datas,
        });
      }
    });
  };*/

  selectUser = () => {
    this.setState({ isShowUser: false });
/*    this.props.model.selectedRowKeys = this.state.selectedRowKeys;
    this.props.model.userIds = this.state.userIds;
    this.props.model.userNames = this.state.userNames;*/
    const ls = this.state.targetKeys;
    const ud = this.state.userDatas;
    let userNames = '';

    ls.forEach(r => {
      console.log(r);
      ud.forEach(f => {
        // eslint-disable-next-line no-unused-expressions
        r === f.key ?  userNames += `${f.title},`: '';
      });

    });

    this.props.model.userIds = this.state.targetKeys;
    this.props.model.userNames = userNames;
  };


  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const braftEditorFormItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 },
    };
    const braftEditorLayout = { md: 30, sm: 20 };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };

    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    const { selectedRowKeys } = this.state;

    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="标题" {...formItemLayout}>
              {type === 'view'
                ? model.messagetitle
                : getFieldDecorator('messagetitle', {
                    initialValue: model.messagetitle,
                    rules: [
                      {
                        required: true,
                        message: '标题必填',
                      },
                      {
                        max: 50,
                        message: '最长50个字符',
                      },
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      {...inputCodeDisabled}
                      maxlength={50}
                      placeholder="标题"
                    />
                  )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="用户类型" {...formItemLayout}>
              {type === 'view'
                ? model.usertype
                : getFieldDecorator('usertype', {
                    initialValue: model.usertype,
                    rules: [
                      {
                        required: true,
                        message: '用户类型必选',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: '100%' }}
                      onChange={value => {
                        model.usertype = value;
                      }}
                    >
                      <option value="">请选择用户类型</option>
                      <option value="21">普通用户</option>
                    </Select>
                  )}
              {model.usertype !== '' && (type === 'add' || type === 'update') && (
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    this.setState({ isShowUser: true });
                    this.getUserList();
                  }}
                >
                  选择用户
                </Button>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="已选用户" {...formItemLayout}>
              {getFieldDecorator('userNames', {
                initialValue: model.userNames,
              })(
                <Input
                  type="text"
                  autocomplete="off"
                  disabled
                  placeholder="默认不动就是全选，请选择你需要指定的用户.."
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Card
          bordered
          hoverable
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title="描述"
        >
          {getFieldDecorator('messagecontent', {
            initialValue: BraftEditor.createEditorState(model.messagecontent),
          })(
            <BraftEditor
              className={styles.my_editor}
              placeholder="请输入描述"
              onChange={editorState => {
                // eslint-disable-next-line react/no-unused-state
                this.setState({ editorState });
              }}
              extendControls={extendControls}
              {...inputCodeDisabledForView}
              {...editorProps}
            />
          )}
        </Card>

        <Modal
          width={700}
          height={500}
          visible={this.state.isShowUser}
          title="选择用户"
          onCancel={() => {
            this.setState({
              isShowUser: false,
            });
          }}
          onOk={this.selectUser}
          confirmLoading={this.state.confirmLoading}
          saveDistance={0}
        >
          <Transfer
            dataSource={this.state.userDatas}
            showSearch
            listStyle={{
              width: 250,
              height: 300,
            }}
            filterOption={this.filterOption}
            operations={['>>', '<<']}
            targetKeys={this.state.targetKeys}
            onChange={this.handleChange}
            //onSearch={this.getUserList}
            render={item => `${item.title}`}
            footer={this.renderFooter}
          />
        </Modal>
     {/*   <Modal
          width={700}
          height={500}
          visible={this.state.isShowUser}
          title="选择用户"
          onCancel={() => {
            this.setState({
              isShowUser: false,
            });
          }}
          onOk={this.selectUser}
          saveDistance={0}
        >
          <div className="content-wrap">
            <Table
              rowSelection={rowSelection}
              columns={this.state.allUserColumns}
              dataSource={this.state.allUserList}
              size="small"
            />
          </div>
        </Modal>*/}
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
